package com.admin.utils.base;

import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;

/**
 * Response请求格式化
 *
 * @author monxz
 * @Date  2020年12月24日上午11:52:35
 * @Des
 *
 */
@Slf4j
public class ResponseFormatter {

	/**
	 * 格式化返回的response
	 * @param res
	 * @throws IOException 
	 */
	public static void  initResponse(HttpServletResponse  response,Object  obj)  {
		response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
       
        try {
        	PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(obj));
        	writer.close();
		} catch (Exception e) {
			log.info("HttpServletResponse Formatter Erroe : {} ",e.getMessage());
		}     
	}
	
	
	/*
	 * 设置浏览器下载响应头
	 */
	public static void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
